package bean;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Component
public class ApiDocMD implements InitializingBean {
    @Value("${application.name}")
    private String applicationName;
    private Configuration cfg = null;

    public String getProp(Properties properties, String prefix, String key){
        return properties.getProperty(prefix+key)!=null?properties.getProperty(prefix+key):key;
    }

    /**
     * 集成FreeMarker生成API Markdown 文件
     * */
    public void createDoc(List<ApiGroup> apis){

        Template request = null;
        try {
            ClassPathResource resource = new ClassPathResource("comment.properties");
            EncodedResource comment = new EncodedResource(resource, "UTF-8");
            Properties properties = PropertiesLoaderUtils.loadProperties(comment);

            request = cfg.getTemplate("api.md.ftl");
            for (ApiGroup api : apis) {
                String fileName = getProp(properties,"safeMode.", api.getSafeMode())
                        + "-"
                        + getProp(properties,"module.", api.getApiModule())
                        + "-"
                        + getProp(properties,"service.", api.getApiService())
                        + ".md";
                api.setApplicationName(applicationName);
                FileWriter fw = new FileWriter(new ClassPathResource("./doc/dev/").getPath()+fileName);
                request.process(api, fw);
            }

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ClassPathResource resource = new ClassPathResource("apitool");
        cfg = new Configuration(Configuration.VERSION_2_3_31);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        try {
            cfg.setDirectoryForTemplateLoading(resource.getFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
